package zsj.androidknife.ThreadPool;

import android.os.Handler;

import zsj.androidknife.utils.BackgroundAction;
import zsj.androidknife.utils.SimpleBackgroundAction;
import zsj.androidknife.utils.SimpleUiAction;
import zsj.androidknife.utils.UiAction;

/**
 * 将Action变为Runnable的Factory
 * Created by Administrator on 2016/4/20 0020.
 */
public class TaskFactory
{
    public static <P, R> Runnable getRunnable(final BackgroundAction<P, R> backgroundAction, final P param)
    {
        if (backgroundAction == null || backgroundAction.isCanceled()) return null;
        return new Runnable()
        {
            @Override
            public void run()
            {
                backgroundAction.doInBackground(param);
            }
        };
    }

    public static <T> Runnable getRunnable(final UiAction<T> uiAction, final T param)
    {
        if (uiAction == null) return null;
        return new Runnable()
        {
            @Override
            public void run()
            {
                uiAction.doInUI(param);
            }
        };
    }

    /**
     * 将backgroundAction和UIAction结合在一起,返回一个Runnable
     * @param mainHandler 含有MainLooper的Handler实例
     * @param backgroundAction
     * @param uiAction
     * @param param
     * @param <P>
     * @param <R>
     * @return
     */
    public static <P, R> Runnable getBgAndUiTask(final Handler mainHandler, final BackgroundAction<P, R> backgroundAction,
                                                 final UiAction<R> uiAction, final P param)
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                R result = null;
                if (backgroundAction != null && !backgroundAction.isCanceled())
                    result = backgroundAction.doInBackground(param);
                mainHandler.post(getRunnable(uiAction, result));
            }
        };
    }

    /**
     * 将SimpleBackgroundAction和SimpleUIAction结合在一起,返回一个Runnable
     * @param mainHandler 含有MainLooper的Handler实例
     * @param backgroundAction
     * @param uiAction
     * @param param
     * @param <P>
     * @param <R>
     * @return
     */
    public static Runnable getBgAndUiTask(final Handler mainHandler, final SimpleBackgroundAction backgroundAction,
                                          final SimpleUiAction uiAction)
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                if (backgroundAction != null && !backgroundAction.isCanceled())
                    backgroundAction.doInBackground();
                if (uiAction != null)
                    mainHandler.post(getRunnable(uiAction));
            }
        };
    }

    public static Runnable getRunnable(final SimpleUiAction uiAction)
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                uiAction.doInUI();
            }
        };
    }

}
